<template>
  <div class="score-list">
    <a-card title="综测分列表">
      <template #extra>
        <a-space>
          <a-button type="primary" @click="showCalculateModal">计算综测分</a-button>
          <a-button @click="$router.push('/scores/ranking')">查看排名</a-button>
          <a-button>导出数据</a-button>
        </a-space>
      </template>

      <a-form layout="inline" class="search-form">
        <a-form-item label="学号/姓名">
          <a-input v-model:value="searchForm.student" placeholder="请输入学号或姓名" style="width: 200px" />
        </a-form-item>
        <a-form-item label="班级">
          <a-input v-model:value="searchForm.class_name" placeholder="请输入班级" style="width: 150px" />
        </a-form-item>
        <a-form-item label="学年">
          <a-select v-model:value="searchForm.year" placeholder="请选择" style="width: 150px" allow-clear>
            <a-select-option :value="2024">2024</a-select-option>
            <a-select-option :value="2023">2023</a-select-option>
            <a-select-option :value="2022">2022</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-table 
        :columns="columns" 
        :data-source="dataSource" 
        :loading="loading"
        bordered 
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'grade'">
            <a-tag color="purple" style="cursor: pointer" @click="showFormula(record)">
              {{ record.grade || 0 }}分
            </a-tag>
          </template>
          <template v-if="column.key === 'zb_grade'">
            <a-tag color="blue" style="cursor: pointer" @click="showFormula(record, 'zb')">
              {{ record.zb_grade || 0 }}分
            </a-tag>
          </template>
          <template v-if="column.key === 'db_grade'">
            <a-tag color="green" style="cursor: pointer" @click="showFormula(record, 'db')">
              {{ record.db_grade || 0 }}分
            </a-tag>
          </template>
          <template v-if="column.key === 'tb_grade'">
            <a-tag color="cyan" style="cursor: pointer" @click="showFormula(record, 'tb')">
              {{ record.tb_grade || 0 }}分
            </a-tag>
          </template>
          <template v-if="column.key === 'za_grade'">
            <a-tag color="orange" style="cursor: pointer" @click="showFormula(record, 'za')">
              {{ record.za_grade || 0 }}分
            </a-tag>
          </template>
          <template v-if="column.key === 'da_grade'">
            <a-tag color="lime" style="cursor: pointer" @click="showFormula(record, 'da')">
              {{ record.da_grade || 0 }}分
            </a-tag>
          </template>
          <template v-if="column.key === 'ta_grade'">
            <a-tag color="geekblue" style="cursor: pointer" @click="showFormula(record, 'ta')">
              {{ record.ta_grade || 0 }}分
            </a-tag>
          </template>
          <template v-if="column.key === 'fail'">
            <a-tag :color="record.fail > 0 ? 'red' : 'green'">
              {{ record.fail || 0 }}门
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a @click="handleView(record)">查看详情</a>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 计算综测分弹窗 -->
    <a-modal 
      v-model:open="calculateVisible" 
      title="计算综测分" 
      width="500px"
      @ok="handleCalculate"
      :confirmLoading="calculateLoading"
    >
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="学年" required>
          <a-select v-model:value="calculateForm.year" placeholder="请选择学年">
            <a-select-option :value="2025">2025</a-select-option>
            <a-select-option :value="2024">2024</a-select-option>
            <a-select-option :value="2023">2023</a-select-option>
            <a-select-option :value="2022">2022</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="年级" required>
          <a-select v-model:value="calculateForm.gradeLevel" placeholder="请选择年级">
            <a-select-option value="大一">大一</a-select-option>
            <a-select-option value="大二">大二</a-select-option>
            <a-select-option value="大三">大三</a-select-option>
            <a-select-option value="大四">大四</a-select-option>
          </a-select>
        </a-form-item>
        <a-alert
          message="计算说明"
          :description="getCalculateDescription()"
          type="info"
          show-icon
        />
      </a-form>
    </a-modal>

    <!-- 计算公式弹窗 -->
    <a-modal 
      v-model:open="formulaVisible" 
      :title="getFormulaTitle()" 
      width="800px"
      :footer="null"
    >
      <a-spin :spinning="formulaLoading">
        <div v-if="formulaData" class="formula-content">
          <!-- 学生信息 -->
          <a-descriptions title="学生信息" :column="2" bordered size="small">
            <a-descriptions-item label="学号">{{ formulaData.student_info.student_id }}</a-descriptions-item>
            <a-descriptions-item label="姓名">{{ formulaData.student_info.student_name }}</a-descriptions-item>
            <a-descriptions-item label="班级">{{ formulaData.student_info.class_name }}</a-descriptions-item>
            <a-descriptions-item label="专业">{{ formulaData.student_info.major }}</a-descriptions-item>
            <a-descriptions-item label="学年" :span="2">{{ formulaData.time }}</a-descriptions-item>
          </a-descriptions>

          <!-- 基本智育分详情 -->
          <template v-if="focusedModule === 'zb'">
            <a-divider>基本智育分详情</a-divider>
            <a-card size="small" title="基本智育分" class="highlight-card">
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-statistic title="分数" :value="formulaData.basic_scores.zb_grade.value" suffix="分" />
                </a-col>
                <a-col :span="8">
                  <a-statistic title="权重" :value="formulaData.basic_scores.zb_grade.weight" />
                </a-col>
                <a-col :span="8">
                  <a-statistic title="加权分" :value="formulaData.basic_scores.zb_grade.weighted_value" suffix="分" />
                </a-col>
              </a-row>
              <a-divider style="margin: 12px 0" />
              <div class="formula-text">
                <strong>计算公式：</strong>
                <pre>{{ formulaData.basic_scores.zb_grade.formula }}</pre>
              </div>
              <div v-if="formulaData.basic_scores.zb_grade.courses.length > 0">
                <strong>课程明细（共{{ formulaData.basic_scores.zb_grade.course_count }}门）：</strong>
                <a-table 
                  :columns="coursesColumns" 
                  :data-source="formulaData.basic_scores.zb_grade.courses" 
                  :pagination="false"
                  size="small"
                  style="margin-top: 8px"
                />
              </div>
            </a-card>
          </template>

          <!-- 基本德育分详情 -->
          <template v-if="focusedModule === 'db'">
            <a-divider>基本德育分详情</a-divider>
            <a-card size="small" title="基本德育分" class="highlight-card">
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-statistic title="分数" :value="formulaData.basic_scores.db_grade.value" suffix="分" />
                </a-col>
                <a-col :span="8">
                  <a-statistic title="权重" :value="formulaData.basic_scores.db_grade.weight" />
                </a-col>
                <a-col :span="8">
                  <a-statistic title="加权分" :value="formulaData.basic_scores.db_grade.weighted_value" suffix="分" />
                </a-col>
              </a-row>
              <a-divider style="margin: 12px 0" />
              <div class="formula-text">{{ formulaData.basic_scores.db_grade.formula }}</div>
            </a-card>
          </template>

          <!-- 基本体育分详情 -->
          <template v-if="focusedModule === 'tb'">
            <a-divider>基本体育分详情</a-divider>
            <a-card size="small" title="基本体育分" class="highlight-card">
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-statistic title="分数" :value="formulaData.basic_scores.tb_grade.value" suffix="分" />
                </a-col>
                <a-col :span="8">
                  <a-statistic title="权重" :value="formulaData.basic_scores.tb_grade.weight" />
                </a-col>
                <a-col :span="8">
                  <a-statistic title="加权分" :value="formulaData.basic_scores.tb_grade.weighted_value" suffix="分" />
                </a-col>
              </a-row>
              <a-divider style="margin: 12px 0" />
              <div class="formula-text">
                <strong>计算公式：</strong>
                <pre>{{ formulaData.basic_scores.tb_grade.formula }}</pre>
              </div>
              <div v-if="formulaData.basic_scores.tb_grade.courses && formulaData.basic_scores.tb_grade.courses.length > 0">
                <strong>体育课程明细（共{{ formulaData.basic_scores.tb_grade.course_count }}门）：</strong>
                <a-table 
                  :columns="coursesColumns" 
                  :data-source="formulaData.basic_scores.tb_grade.courses" 
                  :pagination="false"
                  size="small"
                  style="margin-top: 8px"
                />
              </div>
            </a-card>
          </template>

          <!-- 附加智育分详情 -->
          <template v-if="focusedModule === 'za'">
            <a-divider>附加智育分详情</a-divider>
            <a-card size="small" :title="formulaData.additional_scores.za_grade.name" class="highlight-card">
              <a-statistic :value="formulaData.additional_scores.za_grade.value" suffix="分" />
              <a-divider style="margin: 12px 0" />
              <p>附加智育分由各类学术竞赛、科研项目、发表论文等获得，可后续手动修改。</p>
            </a-card>
          </template>

          <!-- 附加德育分详情 -->
          <template v-if="focusedModule === 'da'">
            <a-divider>附加德育分详情</a-divider>
            <a-card size="small" :title="formulaData.additional_scores.da_grade.name" class="highlight-card">
              <a-statistic :value="formulaData.additional_scores.da_grade.value" suffix="分" />
              <a-divider style="margin: 12px 0" />
              <p>附加德育分由各类志愿服务、社会实践、奖励荣誉等获得，可后续手动修改。</p>
            </a-card>
          </template>

          <!-- 附加体育分详情 -->
          <template v-if="focusedModule === 'ta'">
            <a-divider>附加体育分详情</a-divider>
            <a-card size="small" :title="formulaData.additional_scores.ta_grade.name" class="highlight-card">
              <a-statistic :value="formulaData.additional_scores.ta_grade.value" suffix="分" />
              <a-divider style="margin: 12px 0" />
              <p>附加体育分由各类体育竞赛获奖获得，可后续手动修改。</p>
            </a-card>
          </template>

          <!-- 综测总分详情 -->
          <template v-if="focusedModule === 'all'">
            <a-divider>基本分计算</a-divider>

          <!-- 基本智育分 -->
          <a-card 
            size="small" 
            title="基本智育分" 
            style="margin-bottom: 16px"
            :class="{ 'highlight-card': focusedModule === 'zb' }"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-statistic title="分数" :value="formulaData.basic_scores.zb_grade.value" suffix="分" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="权重" :value="formulaData.basic_scores.zb_grade.weight" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="加权分" :value="formulaData.basic_scores.zb_grade.weighted_value" suffix="分" />
              </a-col>
            </a-row>
            <a-divider style="margin: 12px 0" />
            <div class="formula-text">
              <strong>计算公式：</strong>
              <pre>{{ formulaData.basic_scores.zb_grade.formula }}</pre>
            </div>
            <div v-if="formulaData.basic_scores.zb_grade.courses.length > 0">
              <strong>课程明细（共{{ formulaData.basic_scores.zb_grade.course_count }}门）：</strong>
              <a-table 
                :columns="coursesColumns" 
                :data-source="formulaData.basic_scores.zb_grade.courses" 
                :pagination="false"
                size="small"
                style="margin-top: 8px"
              />
            </div>
          </a-card>

          <!-- 基本德育分 -->
          <a-card 
            size="small" 
            title="基本德育分" 
            style="margin-bottom: 16px"
            :class="{ 'highlight-card': focusedModule === 'db' }"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-statistic title="分数" :value="formulaData.basic_scores.db_grade.value" suffix="分" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="权重" :value="formulaData.basic_scores.db_grade.weight" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="加权分" :value="formulaData.basic_scores.db_grade.weighted_value" suffix="分" />
              </a-col>
            </a-row>
            <a-divider style="margin: 12px 0" />
            <div class="formula-text">{{ formulaData.basic_scores.db_grade.formula }}</div>
          </a-card>

          <!-- 基本体育分 -->
          <a-card 
            size="small" 
            title="基本体育分" 
            style="margin-bottom: 16px"
            :class="{ 'highlight-card': focusedModule === 'tb' }"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-statistic title="分数" :value="formulaData.basic_scores.tb_grade.value" suffix="分" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="权重" :value="formulaData.basic_scores.tb_grade.weight" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="加权分" :value="formulaData.basic_scores.tb_grade.weighted_value" suffix="分" />
              </a-col>
            </a-row>
            <a-divider style="margin: 12px 0" />
            <div class="formula-text">
              <strong>计算公式：</strong>
              <pre>{{ formulaData.basic_scores.tb_grade.formula }}</pre>
            </div>
            <div v-if="formulaData.basic_scores.tb_grade.courses && formulaData.basic_scores.tb_grade.courses.length > 0">
              <strong>体育课程明细（共{{ formulaData.basic_scores.tb_grade.course_count }}门）：</strong>
              <a-table 
                :columns="coursesColumns" 
                :data-source="formulaData.basic_scores.tb_grade.courses" 
                :pagination="false"
                size="small"
                style="margin-top: 8px"
              />
            </div>
          </a-card>

          <a-divider>附加分</a-divider>

          <!-- 附加分 -->
          <a-row :gutter="16" style="margin-bottom: 16px">
            <a-col :span="8">
              <a-card 
                size="small" 
                :title="formulaData.additional_scores.za_grade.name"
                :class="{ 'highlight-card': focusedModule === 'za' }"
              >
                <a-statistic :value="formulaData.additional_scores.za_grade.value" suffix="分" />
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card 
                size="small" 
                :title="formulaData.additional_scores.da_grade.name"
                :class="{ 'highlight-card': focusedModule === 'da' }"
              >
                <a-statistic :value="formulaData.additional_scores.da_grade.value" suffix="分" />
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card 
                size="small" 
                :title="formulaData.additional_scores.ta_grade.name"
                :class="{ 'highlight-card': focusedModule === 'ta' }"
              >
                <a-statistic :value="formulaData.additional_scores.ta_grade.value" suffix="分" />
              </a-card>
            </a-col>
          </a-row>

          <!-- 处分扣分 -->
          <a-divider>扣分明细</a-divider>
          <div v-if="formulaData.deductions.length > 0">
            <a-table 
              :columns="deductionColumns" 
              :data-source="formulaData.deductions" 
              :pagination="false"
              size="small"
            />
            <div style="text-align: right; margin-top: 8px; font-weight: bold">
              总扣分：<span style="color: red">{{ formulaData.total_deduction }}</span> 分
            </div>
          </div>
          <div v-else style="text-align: center; color: #999">
            无扣分记录
          </div>

            <!-- 最终计算 -->
            <a-divider>最终计算</a-divider>
            <a-card size="small">
              <pre class="final-formula">{{ formulaData.final_formula }}</pre>
              <a-divider style="margin: 12px 0" />
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-statistic title="基本分合计" :value="formulaData.summary.basic_total" suffix="分" :precision="2" />
                </a-col>
                <a-col :span="6">
                  <a-statistic title="附加分合计" :value="formulaData.summary.additional_total" suffix="分" :precision="2" />
                </a-col>
                <a-col :span="6">
                  <a-statistic title="扣分合计" :value="formulaData.summary.deduction_total" suffix="分" :precision="2" />
                </a-col>
                <a-col :span="6">
                  <a-statistic 
                    title="最终综测分" 
                    :value="formulaData.final_score" 
                    suffix="分" 
                    :precision="2"
                    :value-style="{ color: '#3f8600', fontWeight: 'bold' }"
                  />
                </a-col>
              </a-row>
            </a-card>
          </template>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { scoreAPI } from '@/api/score'
import type { Score, ScoreFormula } from '@/api/score'

const router = useRouter()
const loading = ref(false)
const dataSource = ref<Score[]>([])

const searchForm = reactive({
  student: '',
  year: undefined as number | undefined,
  class_name: ''
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 70 },
  { title: '学号', dataIndex: 'student_id', key: 'student_id', width: 120 },
  { title: '姓名', dataIndex: 'student_name', key: 'student_name', width: 100 },
  { title: '学年', dataIndex: 'time', key: 'time', width: 100 },
  { title: '综测总分', key: 'grade', width: 100 },
  { title: '基本智育分', key: 'zb_grade', width: 120 },
  { title: '基本德育分', key: 'db_grade', width: 120 },
  { title: '基本体育分', key: 'tb_grade', width: 120 },
  { title: '附加智育分', key: 'za_grade', width: 120 },
  { title: '附加德育分', key: 'da_grade', width: 120 },
  { title: '附加体育分', key: 'ta_grade', width: 120 },
  { title: '挂科数', key: 'fail', width: 80 },
  { title: '操作', key: 'action', width: 100 }
]

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    loadData()
  }
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.value.current,
      page_size: pagination.value.pageSize
    }
    
    // 添加筛选条件
    if (searchForm.year) {
      params.time = searchForm.year
    }
    if (searchForm.student) {
      params.student = searchForm.student
    }
    if (searchForm.class_name) {
      params.class_name = searchForm.class_name
    }
    
    const res = await scoreAPI.getScoreList(params)
    dataSource.value = res.data.results
    pagination.value.total = res.data.count
  } catch (error: any) {
    message.error('加载数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.student = ''
  searchForm.year = undefined
  searchForm.class_name = ''
  pagination.value.current = 1
  loadData()
}

// 查看详情
const handleView = (record: Score) => {
  router.push(`/scores/detail/${record.id}`)
}

// 计算综测分
const calculateVisible = ref(false)
const calculateLoading = ref(false)
const calculateForm = reactive({
  year: undefined as number | undefined,
  gradeLevel: undefined as string | undefined
})

// 显示计算弹窗
const showCalculateModal = () => {
  calculateForm.year = searchForm.year || new Date().getFullYear()
  calculateForm.gradeLevel = undefined
  calculateVisible.value = true
}

// 获取计算说明
const getCalculateDescription = () => {
  if (calculateForm.gradeLevel === '大三' || calculateForm.gradeLevel === '大四') {
    return '系统将根据该学年的成绩数据自动计算所有学生的综测分。' +
      '计算规则：基本智育分(非体育课平均分×70%) + 基本德育分(80×20%) + 基本体育分10分(满分) + 附加分 - 处分扣分。'
  }
  return '系统将根据该学年的成绩数据自动计算所有学生的综测分。' +
    '计算规则：基本智育分(非体育课平均分×70%) + 基本德育分(80×20%) + 基本体育分(体育课平均分×10%) + 附加分 - 处分扣分。'
}

// 执行计算
const handleCalculate = async () => {
  if (!calculateForm.year) {
    message.error('请选择学年')
    return
  }
  
  if (!calculateForm.gradeLevel) {
    message.error('请选择年级')
    return
  }
  
  calculateLoading.value = true
  try {
    const res = await scoreAPI.calculateScore({
      time: calculateForm.year,
      grade_level: calculateForm.gradeLevel
    })
    
    const data = res.data.data
    message.success(`计算完成！成功：${data.success_count} 条，失败：${data.fail_count} 条`)
    
    // 如果有错误信息，显示详情
    if (data.errors && data.errors.length > 0) {
      console.log('计算错误详情：', data.errors)
    }
    
    calculateVisible.value = false
    loadData() // 重新加载数据
  } catch (error: any) {
    message.error('计算失败: ' + (error.response?.data?.message || error.message))
  } finally {
    calculateLoading.value = false
  }
}

// 计算公式弹窗
const formulaVisible = ref(false)
const formulaLoading = ref(false)
const formulaData = ref<ScoreFormula | null>(null)
const focusedModule = ref<'all' | 'zb' | 'db' | 'tb' | 'za' | 'da' | 'ta'>('all')  // 记录当前查看的模块

// 课程表格列
const coursesColumns = [
  { title: '课程名称', dataIndex: 'course_name', key: 'course_name' },
  { title: '成绩', dataIndex: 'grade', key: 'grade', width: 100 }
]

// 扣分表格列
const deductionColumns = [
  { title: '类型', dataIndex: 'type', key: 'type', width: 80 },
  { title: '类别', dataIndex: 'sort', key: 'sort', width: 100 },
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '级别', dataIndex: 'ranks', key: 'ranks', width: 100 },
  { title: '扣分', dataIndex: 'score', key: 'score', width: 100 }
]

// 显示计算公式
const showFormula = async (record: Score, module?: 'zb' | 'db' | 'tb' | 'za' | 'da' | 'ta') => {
  formulaVisible.value = true
  formulaLoading.value = true
  formulaData.value = null
  focusedModule.value = (module as 'all' | 'zb' | 'db' | 'tb' | 'za' | 'da' | 'ta') || 'all'  // 记录点击的模块
  
  try {
    const res = await scoreAPI.getScoreFormula(record.id)
    formulaData.value = res.data.data
  } catch (error: any) {
    message.error('获取计算公式失败: ' + (error.response?.data?.message || error.message))
    formulaVisible.value = false
  } finally {
    formulaLoading.value = false
  }
}

// 获取弹窗标题
const getFormulaTitle = () => {
  const moduleNames: Record<string, string> = {
    'all': '综测分计算公式详情',
    'zb': '基本智育分计算详情',
    'db': '基本德育分计算详情',
    'tb': '基本体育分计算详情',
    'za': '附加智育分详情',
    'da': '附加德育分详情',
    'ta': '附加体育分详情'
  }
  return moduleNames[focusedModule.value] || '综测分计算公式详情'
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.formula-content {
  max-height: 70vh;
  overflow-y: auto;
}

.formula-text {
  padding: 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 14px;
}

.formula-text pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.final-formula {
  background-color: #e6f7ff;
  padding: 16px;
  border-radius: 4px;
  border-left: 4px solid #1890ff;
  font-size: 14px;
  line-height: 1.8;
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 高亮当前查看的模块 */
.highlight-card {
  border: 2px solid #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.highlight-card :deep(.ant-card-head) {
  background-color: #e6f7ff;
}
</style>
